<template>
  <div class="profile-completion-container">
    <div class="completion-box">
      <div class="header-section">
        <div class="icon-wrapper">
          <i class="icon-user-tie"></i>
        </div>
        <h2>完善教师信息</h2>
        <p class="subtitle">请完善您的教学信息以开始授课</p>
      </div>

      <form @submit.prevent="handleSubmit" class="completion-form">
        <!-- 错误提示 -->
        <div v-if="errorMessage" class="error-message">
          <i class="icon-alert-circle"></i>
          {{ errorMessage }}
        </div>

        <!-- 成功提示 -->
        <div v-if="successMessage" class="success-message">
          <i class="icon-check-circle"></i>
          {{ successMessage }}
        </div>

        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">
            <i class="icon-user"></i>
            基本信息
          </h3>
          
          <div class="form-row">
            <div class="form-group">
              <label>教工号 <span class="required">*</span></label>
              <input
                v-model="formData.teacher_id"
                type="text"
                required
                placeholder="请输入教工号"
                maxlength="20"
                :disabled="loading"
              />
            </div>
            
            <div class="form-group">
              <label>讲师姓名 <span class="required">*</span></label>
              <input
                v-model="formData.name"
                type="text"
                required
                placeholder="请输入真实姓名"
                maxlength="50"
                :disabled="loading"
              />
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label>身份证号 <span class="required">*</span></label>
              <input
                v-model="formData.id_card"
                type="text"
                required
                placeholder="请输入身份证号"
                maxlength="18"
                :disabled="loading"
              />
            </div>
            
            <div class="form-group">
              <label>联系方式 <span class="required">*</span></label>
              <input
                v-model="formData.phone"
                type="tel"
                required
                placeholder="请输入手机号"
                maxlength="20"
                :disabled="loading"
              />
            </div>
          </div>
        </div>

        <!-- 教学信息 -->
        <div class="form-section">
          <h3 class="section-title">
            <i class="icon-book"></i>
            教学信息
          </h3>
          
          <div class="form-row">
            <div class="form-group">
              <label>教学方向 <span class="required">*</span></label>
              <input
                v-model="formData.specialty"
                type="text"
                required
                placeholder="请输入教学专业方向"
                maxlength="100"
                :disabled="loading"
              />
            </div>
            
            <div class="form-group">
              <label>职称级别 <span class="required">*</span></label>
              <input
                v-model="formData.level"
                type="text"
                required
                placeholder="如：讲师、副教授、教授等"
                maxlength="50"
                :disabled="loading"
              />
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label>入职时间 <span class="required">*</span></label>
              <input
                v-model="formData.hire_date"
                type="date"
                required
                :disabled="loading"
              />
            </div>
            
            <div class="form-group">
              <label>教师分类 <span class="required">*</span></label>
              <select v-model="formData.category_id" required :disabled="loading">
                <option value="">请选择教师分类</option>
                <option v-for="category in categories" :key="category.id" :value="category.id">
                  {{ category.name }}
                </option>
              </select>
            </div>
          </div>
        </div>

        <!-- 其他信息 -->
        <div class="form-section">
          <h3 class="section-title">
            <i class="icon-info"></i>
            其他信息
          </h3>
          
          <div class="form-group">
            <label>教育经历 <span class="required">*</span></label>
            <textarea
              v-model="formData.education"
              required
              placeholder="请详细描述您的教育背景和学历信息"
              rows="4"
              :disabled="loading"
            ></textarea>
          </div>

          <div class="form-group">
            <label>备注</label>
            <textarea
              v-model="formData.notes"
              placeholder="其他需要说明的信息"
              rows="3"
              :disabled="loading"
            ></textarea>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <button type="button" @click="logout" class="logout-btn">
            退出登录
          </button>
          <button type="submit" class="submit-btn" :disabled="loading">
            <i v-if="loading" class="icon-loading"></i>
            {{ loading ? '提交中...' : '完成信息完善' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()

const loading = ref(false)
const errorMessage = ref('')
const successMessage = ref('')

// 下拉选项数据
const categories = ref([])

// 表单数据
const formData = reactive({
  teacher_id: '',
  name: '',
  phone: '',
  id_card: '',
  specialty: '',
  hire_date: '',
  education: '',
  level: '',
  category_id: '',
  notes: ''
})

// API 基础配置
// const API_BASE_URL = process.env.VUE_APP_API_BASE_URL || 'http://localhost:8000'
const API_BASE_URL = '/api'


// 获取教师分类列表
const fetchCategories = async () => {
  try {
    // 使用固定的教师分类数据
    categories.value = [
      { id: 126, name: '高级讲师' },
      { id: 127, name: '中级讲师' },
      { id: 128, name: '初级讲师' },
      { id: 129, name: '客座讲师' }
    ];
  } catch (error) {
    console.error('设置分类列表失败:', error);
  }
}

// 提交教师信息
const handleSubmit = async () => {
  errorMessage.value = ''
  successMessage.value = ''
  loading.value = true

  try {
    const response = await fetch(`${API_BASE_URL}/create-profile`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authStore.accessToken}`
      },
      body: JSON.stringify({
        teacher_data: formData
      })
    })

    if (!response.ok) {
      const errorData = await response.json()
      // 处理常见错误信息
      const errorMessages = {
        '教工号已存在': '教工号已被使用，请检查后重新输入',
        '身份证号已存在': '身份证号已被注册，请检查后重新输入'
      }
      const errorMsg = errorMessages[errorData.detail] || errorData.detail || '信息提交失败'
      throw new Error(errorMsg)
    }

    const result = await response.json()
    successMessage.value = '教师信息完善成功！即将跳转到主页面...'

    // 更新用户信息状态
    authStore.markProfileCompleted(result.data.profile)

     // 确保用户信息已更新
    await authStore.fetchUserProfile()

    // 2秒后跳转到主页面
    router.replace('/teacher/dashboard')

  } catch (error) {
    console.error('提交失败:', error)
    errorMessage.value = error.message || '信息提交失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 退出登录
const logout = () => {
  authStore.clearAuth()
  router.push('/login')
}

// 页面加载时获取选项数据
onMounted(() => {
  fetchCategories()
})
</script>

<style scoped>
/* 与学员界面相同的样式 */
.profile-completion-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.completion-box {
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0,0,0,0.1);
  width: 100%;
  max-width: 800px;
  max-height: 90vh;
  overflow-y: auto;
}

.header-section {
  text-align: center;
  padding: 40px 40px 20px;
  border-bottom: 1px solid #E5E7EB;
}

.icon-wrapper {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #4F46E5, #7C3AED);
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;
  box-shadow: 0 8px 20px rgba(79, 70, 229, 0.3);
}

.icon-wrapper i {
  font-size: 36px;
  color: white;
}

.header-section h2 {
  margin: 0 0 8px 0;
  color: #1F2937;
  font-size: 24px;
  font-weight: 600;
}

.subtitle {
  margin: 0;
  color: #6B7280;
  font-size: 14px;
}

.completion-form {
  padding: 40px;
}

.error-message {
  background: #FEF2F2;
  border: 1px solid #FECACA;
  color: #DC2626;
  padding: 12px 16px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  margin-bottom: 20px;
}

.success-message {
  background: #F0FDF4;
  border: 1px solid #BBF7D0;
  color: #16A34A;
  padding: 12px 16px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  margin-bottom: 20px;
}

.form-section {
  margin-bottom: 32px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #1F2937;
  margin-bottom: 20px;
  padding-bottom: 8px;
  border-bottom: 2px solid #E5E7EB;
}

.section-title i {
  color: #4F46E5;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.required {
  color: #DC2626;
}

.form-group input,
.form-group select,
.form-group textarea {
  padding: 12px 16px;
  border: 2px solid #E5E7EB;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.2s;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #4F46E5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}

.form-group input:disabled,
.form-group select:disabled,
.form-group textarea:disabled {
  background-color: #F9FAFB;
  cursor: not-allowed;
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
}

.form-actions {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #E5E7EB;
  display: flex;
  justify-content: center;
  gap: 16px;
}

.submit-btn {
  padding: 14px 32px;
  background: linear-gradient(135deg, #4F46E5, #7C3AED);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.4);
}

.submit-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform:none;
}

.logout-btn {
  padding: 14px 32px;
  background: #F3F4F6;
  color: #4B5563;
  border: 1px solid #D1D5DB;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.logout-btn:hover {
  background: #E5E7EB;
}

.icon-loading {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .completion-box {
    margin: 10px;
    max-height: calc(100vh - 20px);
  }
  
  .header-section,
  .completion-form {
    padding: 20px;
  }
  
  .form-row {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .section-title {
    font-size: 16px;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>